<template>
    <div>
        <div class="e-m-t-45">
            <div class="flex">
                <div class="e-flex-1">
                    <el-button type="primary" icon="el-icon-plus" plain @click="dialogVisible = true;">新增小哥</el-button>
                </div>
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item label="">
                        <el-input placeholder="请输入" v-model="key" prefix-icon="el-icon-search" clearable
                            @input="getList"></el-input>
                    </el-form-item>
                    <el-form-item class="e-m-r-0">
                        <el-button type="primary" @click="getList">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <custom-table storageKey="brother-list" :table-data="tableData" :columns="tableColumns" :actions="tableActions"
            :total="total" :page-index="pageIndex" :page-size="pageSize" @page-change="handlePagination"
            @action-click="handleTableAction">
            <!-- 自定义接单地区列 -->
            <template #citys="scope">
                <el-tag v-for="(item, index) in scope.row.citys" :key="index" size="mini" class="e-m-r-10">{{
                        item.cityname }}</el-tag>
            </template>
        </custom-table>
        <!-- 添加小哥 -->
        <el-dialog title="添加小哥" :visible.sync="dialogVisible" width="500px">
            <el-form ref="addForm" :model="addForm" label-width="140px" :rules="rules">
                <el-form-item label="手机号码" prop="mobile">
                    <autocompleteCustomer v-model="addForm.mobile" placeholder="请输入手机号码" @select="selectCustomer"
                        @change="(val) => { addForm.mobile = val; addForm.userId = 0;nameDisabled = false }"
                        @input="() => $refs.addForm.validateField('mobile')"
                        @blur="() => $refs.addForm.validateField('mobile')">
                    </autocompleteCustomer>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="addForm.name" placeholder="请输入名称" :disabled="nameDisabled"
                        @input="$refs.addForm.validateField('name')"
                        @blur="$refs.addForm.validateField('name')"></el-input>
                </el-form-item>
                <el-form-item label="限定接单地区(选填)" prop="cityids">
                    <cityList v-model="addForm.cityids" :multiple="true" @change="SelectCityList"></cityList>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addBrother">确定</el-button>
            </span>
        </el-dialog>
        <!-- 小哥设置 -->
        <el-dialog title="小哥设置" :visible.sync="settingDialogVisible" width="500px">
            <el-form ref="settingForm" :model="settingForm" label-width="140px">
                <el-form-item label="修改接单地区" prop="cityids">
                    <cityList v-model="settingForm.cityids" :multiple="true"></cityList>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="settingDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="setBrother">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    mapState
} from 'vuex';

import autocompleteCustomer from "@/components/form-select-type/autocompleteCustomer.vue"
import franchiseStaffList from "@/components/form-select-type/franchiseStaffList.vue"
import cityList from '@/components/form-select-type/cityList.vue'
export default {
    components: {
        franchiseStaffList,
        cityList,
        autocompleteCustomer
    },
    props: {
        franchiseId: {
            type: [Number, String],
            default: 0
        }
    },
    data() {
        // 手机号码校验规则
        const validateMobile = (rule, value, callback) => {
            if (!value) {
                callback(new Error('手机号码不能为空'));
            } else if (!/^1[3-9]\d{9}$/.test(value)) {
                callback(new Error('请输入有效的手机号码'));
            } else {
                callback();
            }
        };
        return {
            rules: {
                mobile: [
                    { required: true, validator: validateMobile, trigger: 'blur' },
                    { min: 11, max: 11, message: '手机号码长度必须为11位', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '名称不能为空', trigger: 'blur' },
                    // { min: 2, max: 50, message: '名称长度在2到50个字符', trigger: 'blur' }
                ]
            },
            key: "",
            // 添加小哥
            dialogVisible: false,
            addForm: {
                userId: null,
                mobile: "",
                name: "",
                quota: 0,
                cityids: []
            },
            nameDisabled: false,
            // 小哥设置
            settingDialogVisible: false,
            settingForm: {
                userId: null,
                quota: 0,
                cityids: []
            },
            // 
            total: 0,
            pageIndex: 1,
            pageSize: 10,
            tableData: [],
            tableColumns: [
                {
                    prop: 'name',
                    label: '姓名',
                },
                {
                    prop: 'mobile',
                    label: '手机号码',
                },
                {
                    prop: 'citys',
                    label: '限定接单地区',
                    slotName: 'citys'
                },
            ],
            tableActions: [
                {
                    name: 'setting',
                    label: '设置'
                },
                {
                    name: 'acdelete',
                    label: '移除'
                }
            ],
        }
    },
    mounted() {
        this.getList()
    },
    computed: {
        ...mapState({
            operator: state => state.operator
        }),
    },
    methods: {
        selectCustomer(obj) {
            console.log('selectCustomer', obj)
            this.nameDisabled = true
            this.addForm.name = obj.name
            this.addForm.userId = obj.id
            // this.addForm.mobile = obj.mobile
        },
        getList() {
            this.$axios.post('/Franchise/Brother/List', {
                "PageIndex": this.pageIndex,
                "pageSize": this.pageSize,
                "Key": this.key,
                "franchiseId": this.franchiseId
            }).then((res) => {
                console.log(res)

                this.tableData = res.rows;
                this.total = res.total;
            }).catch(() => {

            })
        },
        // 翻页操作处理
        handlePagination({ pageIndex, pageSize }) {
            this.pageIndex = pageIndex
            this.pageSize = pageSize
            this.getList(false) // 获取新数据
        },
        // 操作按钮点击事件
        handleTableAction({ action, row, event }) {
            switch (action) {
                case 'acdelete':
                    this.acdelete(row.userid)
                    break
                case 'setting':
                    this.settingForm.userId = row.userid
                    this.settingForm.cityids = []
                    row.citys.forEach(item => {
                        this.settingForm.cityids.push(item.cityid)
                    });

                    this.settingDialogVisible = true
                    break
            }
        },
        addBrother() {
            // console.log({
            //     userId: this.addForm.userId,
            //     franchiseId: this.franchiseId,
            //     mobile: this.addForm.mobile,
            //     name: this.addForm.name,
            //     // name: '猿哥'+ this.addForm.mobile.slice(-4),
            //     cityids: this.addForm.cityids,
            //     quota: 0
            // })
            let cityids = 0
            if (this.addForm.cityids > 0) {
                cityids = this.addForm.cityids
            } else {
                if (this.operator?.city?.cityid > 0) {
                    cityids = [this.operator.city.cityid]
                }
            }
            if (cityids == 0) {
                this.$message.error('请选择接单地区')
                return
            }
            this.$refs.addForm.validate((valid) => {
                if (valid) {
                    this.$axios.post('/Franchise/Brother/Add', {
                        franchiseId: this.franchiseId,
                        mobile: this.addForm.mobile,
                        name: this.addForm.name,
                        cityids: cityids,
                        quota: 0
                        // UserId: this.addForm.userId
                    }).then((res) => {
                        console.log(res)
                        this.dialogVisible = false
                        this.getList()
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
            
        },
        setBrother() {

            this.$axios.post('/Franchise/Brother/Edit', {
                userId: this.settingForm.userId,
                cityids: this.settingForm.cityids,
                quota: 0
            }).then((res) => {
                console.log(res)
                this.settingDialogVisible = false
                this.getList()
            })
        },
        SelectCityList(v) { //接单地区
            console.log('SelectCityList', v)
            this.addForm.cityids = v

        },
        // switchManagerState(event, row) {
        //     this.$axios.get(`/store/staff/SetManager?storeId=${this.$route.query.id}&UserId=${row.id}&isSet=${row.ismanager}`).then((res) => {
        //         this.$message.success(res.msg);
        //     }).catch((err) => {
        //         this.getList()
        //     })
        // },
        // 移除
        acdelete(id) {
            this.$confirm('此操作将移除该小哥, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.get(`/Franchise/Brother/Remove?franchiseId=${this.franchiseId}&UserId=${id}`).then((res) => {
                    console.log(res)
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    });
                    this.getList()
                })
            }).catch(() => {

            });
        },
    }
}
</script>

<style scoped></style>